<template>
  <div ref="chart" :style="{ width: '100%', height: height<=100?`${height}%`:`${height}px` }"></div>
</template>

<script>
export default {
  props: {
    reset: {
      type: Boolean,
      default: true
    },
    height: {
      type: Number,
      default: 400
    },
    option: {
      type: Object,
      default: () => {
        return {
          title: {
            text: '某站点用户访问来源',
            subtext: '纯属虚构',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
          },
          series: [
            {
              name: '访问来源',
              type: 'pie',
              radius: '55%',
              center: ['50%', '60%'],
              data: [
                { value: 335, name: '直接访问' },
                { value: 310, name: '邮件营销' },
                { value: 234, name: '联盟广告' },
                { value: 135, name: '视频广告' },
                { value: 1548, name: '搜索引擎' }
              ],
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }
      }
    }
  },
  data () {
    return {
      chart: null
    }
  },
  watch: {
    option: { // 监听的对象
      deep: true, // 深度监听设置为 true
      handler: function (newVal) {
        if (this.reset) {
          this.chart.clear()
        }
        this.chart.setOption(newVal)
      }
    },
    style () {
      this.chart.resize()
    }
  },
  mounted () {
    this.initChart()
  },
  methods: {
    resize () {
      this.chart.resize()
    },
    clear () {
      this.chart.clear()
    },
    setOption (option) {
      this.chart.setOption(option)
    },
    initChart () {
      const that = this
      that.chart = that.$echarts.init(that.$refs.chart)
      that.chart.resize()
      window.addEventListener('resize', () => {
        that.chart.resize()
      })
      that.chart.setOption(that.option)
      that.chart.on('click', (p) => {
        that.$emit('click', p)
      })
    }
  }
}
</script>
<style lang="less" scoped>
</style>
